import axios from 'axios'
import router from '@/router/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import store from '@/store/index';
// const store = useStore();
const service = axios.create({
  baseURL: `${import.meta.env.VITE_APP_BASE_API}`, // url = base url + request url
  timeout: 5000
  // withCredentials: true // send cookies when cross-domain requests
})

// Request interceptors
service.interceptors.request.use(
  (config: any) => {
    // Add X-Access-Token header to every request, you can add other custom headers here
    if (localStorage.getItem('token')) {
      config.headers['Authorization'] = localStorage.getItem('token')
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code !== 200) {
      if (res.code === 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        // console.log(store);
        store.commit("updataUser", {});
        store.commit("updateLoginState", false);
        ElMessageBox.confirm(
          '登录超时或者未登陆，您可以继续停留在该页面或者重新登录',
          '提示',
          {
            confirmButtonText: '登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          router.push('/login')
        }).catch(()=>{
          // location.reload()
        })
        return
      }
      ElMessage({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    } else {
      return res
    }
  },
  (error) => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service